#include "GraphicsScene.h"
#include "MainWindow.h"
#include "Marker.h"

GraphicsScene::GraphicsScene(QObject *parent): QGraphicsScene(parent)
{
}
void GraphicsScene::mouseDoubleClickEvent( QGraphicsSceneMouseEvent * event )
{
   if (event->button() != Qt::LeftButton)
        return;
    QPointF *pos=&event->scenePos();
    addMarker(pos);
    QGraphicsScene::mouseDoubleClickEvent(event);
}

void GraphicsScene::addMarker(QPointF *xy)
{
    Marker *marker = new Marker;
    setupMarker(marker,xy);

}

void GraphicsScene::setupMarker(Marker *marker,QPointF *xy)
{

    int size=MainWindow::getSize();
    QColor col=MainWindow::getColor();
    Marker::Shape shp= Marker::Shape(MainWindow::getShape()-1);

    marker->setPos(xy->x(),xy->y());
    marker->setSize(size);
    marker->setShape(shp);
    marker->setOutlineColor(col);
    marker->markX(xy->x());
    marker->markY(xy->y());


    addItem(marker);
    markerlist.clear();
    markerlist.append(this->items());

    seqNumber=markerlist.size();

    clearSelection();
    marker->setSelected(true);
    bringToFront();

    emit markerPos(marker->getXpos(),marker->getYpos());
}

void GraphicsScene::bringToFront()
{
    ++maxZ;
    setZValue(maxZ);
}
void GraphicsScene::sendToBack()
{
    --minZ;
    setZValue(minZ);
}

void GraphicsScene::setZValue(int z)
{
    Marker *Marker = selectedMarker();
    if (Marker)
        Marker->setZValue(z);
}

Marker *GraphicsScene::selectedMarker() const
{
    QList<QGraphicsItem *> items = selectedItems();

    if (items.count() == 1)
    {     
        return dynamic_cast<Marker *>(items.first());
    }

    else {
        return 0;
    }
}

